import React, { PureComponent } from 'react';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import { Form, Input, notification, Button, Row, Col, Popover, Progress } from 'antd';
import styles from './ChangePassword.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { changePassword } from '../../services/session-auth';

const FormItem = Form.Item;

const passwordStatusMap = {
    ok: <div className={styles.success}>强度：强</div>,
    pass: <div className={styles.warning}>强度：中</div>,
    poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
    ok: 'success',
    pass: 'normal',
    poor: 'exception',
};
@connect()
@Form.create()
class ChangePassword extends PureComponent {
    state = {
        help: '',
        confirmDirty: false,
        visible: false,
        loading: false,
    };
    submitHandle(e) {
        e.preventDefault();

        const { form, dispatch } = this.props;
        form.validateFields((e, values) => {
            if (!e) {
                this.setState({
                    visible: false,
                });

                const { oldPwd, password: newPwd } = values;
                changePassword({ oldPwd, newPwd }).then(({ response, error }) => {
                    if (response) {
                        notification.success({
                            message: '密码修改成功',
                            description: '请重新登录',
                            duration: 2,
                            onClose: () => {
                                dispatch(routerRedux.replace('/user/login'));
                            },
                        });
                    }
                    if (error) {
                        const { message, status } = error;
                        notification.error({
                            message: '密码修改失败',
                            description: message ? message : codeMessage[status],
                        });
                    }
                });
            }
        });
    }

    checkConfirm = (rule, value, callback) => {
        const { form } = this.props;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入的密码不匹配!');
        } else {
            callback();
        }
    };
    getPasswordStatus = () => {
        const { form } = this.props;
        const value = form.getFieldValue('password');
        if (value && value.length > 9) {
            return 'ok';
        }
        if (value && value.length > 5) {
            return 'pass';
        }
        return 'poor';
    };
    checkPassword = (rule, value, callback) => {
        if (!value) {
            this.setState({
                help: '请输入密码！',
                visible: !!value,
            });
            callback('error');
        } else {
            this.setState({
                help: '',
            });
            const { visible, confirmDirty } = this.state;
            if (!visible) {
                this.setState({
                    visible: !!value,
                });
            }
            if (value.length < 6) {
                callback('error');
            } else {
                const { form } = this.props;
                if (value && confirmDirty) {
                    form.validateFields(['confirm'], { force: true });
                }
                callback();
            }
        }
    };
    renderPasswordProgress = () => {
        const { form } = this.props;
        const value = form.getFieldValue('password');
        const passwordStatus = this.getPasswordStatus();
        return value && value.length ? (
            <div className={styles[`progress-${passwordStatus}`]}>
                <Progress
                    status={passwordProgressMap[passwordStatus]}
                    className={styles.progress}
                    strokeWidth={6}
                    percent={value.length * 10 > 100 ? 100 : value.length * 10}
                    showInfo={false}
                />
            </div>
        ) : null;
    };
    render() {
        const {
            form: { getFieldDecorator },
        } = this.props;
        const { help, visible } = this.state;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 19, offset: 1 },
            },
        };

        return (
            <PageHeaderLayout>
                <div className={styles.container}>
                    <div className={styles.content}>
                        <Form onSubmit={this.submitHandle.bind(this)}>
                            <FormItem {...formItemLayout} label="原密码">
                                {getFieldDecorator('oldPwd', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入原密码',
                                        },
                                    ],
                                })(<Input type="password" />)}
                            </FormItem>
                            <FormItem help={help} {...formItemLayout} label="新密码">
                                <Popover
                                    content={
                                        <div style={{ padding: '4px 0' }}>
                                            {passwordStatusMap[this.getPasswordStatus()]}
                                            {this.renderPasswordProgress()}
                                            <div style={{ marginTop: 10 }}>
                                                请至少输入 6 个字符。请不要使用容易被猜到的密码。
                                            </div>
                                        </div>
                                    }
                                    overlayStyle={{ width: 240 }}
                                    placement="right"
                                    visible={visible}
                                >
                                    {getFieldDecorator('password', {
                                        rules: [
                                            {
                                                validator: this.checkPassword,
                                            },
                                        ],
                                    })(<Input type="password" />)}
                                </Popover>
                            </FormItem>
                            <FormItem {...formItemLayout} label="确认密码">
                                {getFieldDecorator('confirim', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请确认密码！',
                                        },
                                        {
                                            validator: this.checkConfirm,
                                        },
                                    ],
                                })(<Input type="password" />)}
                            </FormItem>

                            <FormItem>
                                <Row type="flex" justify="end" gutter={12}>
                                    <Col>
                                        <Button>返回</Button>
                                    </Col>
                                    <Col>
                                        <Button type="primary" htmlType="submit">
                                            提交
                                        </Button>
                                    </Col>
                                </Row>
                            </FormItem>
                        </Form>
                    </div>
                </div>
            </PageHeaderLayout>
        );
    }
}

export default ChangePassword;
